<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *      [PinTuXiu] (C)2001-2099 ONightjar.com Pintuxiu.com.
 *      This is NOT a freeware, use is subject to license terms
 */

class activity_db extends Model{
	public $pk = 'id';
	public $table = 'ptx_activity';
	
	var $linker = array(
			'fromuser'=>array(
					'type' => 'hasone',
					'map' => 'fromuser',
					'mapkey' => 'user_id',
					'ftable' => 'ptx_user',
					'fkey' => 'user_id',
					'enabled' => true
			),
			'touser'=>array(
					'type' => 'hasone',
					'map' => 'touser',
					'mapkey' => 'to_user_id',
					'ftable' => 'ptx_user',
					'fkey' => 'user_id',
					'enabled' => true
			)
	);
	
	
	var $select_fields = " ptx_activity.*,fromuser.user_id as fuser_id,fromuser.nickname as fnickname,touser.user_id as tuser_id,touser.nickname as tnickname ";
	
	private function init_conditions($conditions){
		$conditions_message = NULL;
		
		if(isset($conditions['user_id'])){
			$user_id = $this->escape($conditions['user_id']);
			$conditions_message .= "AND ptx_activity.user_id={$user_id} ";
		}
		if(isset($conditions['to_user_id'])){
			$user_id = $this->escape($conditions['to_user_id']);
			$conditions_message .= "AND ptx_activity.to_user_id={$user_id} ";
		}
		if(strpos($conditions_message, 'AND') === 0){
			$conditions_message = substr($conditions_message, 3);
		}
		return $conditions_message;
	}
	
	public function search($conditions=NULL,$page,$pagesize,$fields = null,$sort=null){
		if(is_array($conditions)) $conditions = $this->init_conditions($conditions);
		$sort = isset($sort)?$sort:" ptx_activity.id DESC ";
		$fields = isset($fields)?$fields:$this->select_fields;
		return $this->pager($page, $pagesize)->findAllJoin($conditions,$sort,$fields);
	}
	
	public function getActivityByUser($uid){
		return $this->findAll(array('user_id'=>$uid)," ptx_activity.id DESC ", null, 6);
	}
	
	public function getActivityByToUser($uid){
		return $this->findAll(array('to_user_id'=>$uid,'is_read'=>0)," ptx_activity.id DESC ");
	}
	
	public function getActivityCountByToUser($uid){
		return $this->findCount(array('to_user_id'=>$uid,'is_read'=>0));
	}
	
	public function addActivity($uid,$act,$title='',$relid=0,$touid=0){
		$this->create(array('user_id'=>$uid,'act_code'=>$act,'act_title'=>$title,'rel_id'=>$relid,'create_time'=>TIMESTAMP,'to_user_id'=>$touid));
		$this->clearActivity($uid,50);
	}
	
	public function clearActivity($uid,$maxnum=5){
		$act = $this->findSql("SELECT id from {$this->tbl_name} WHERE user_id='{$uid}' ORDER BY id DESC LIMIT {$maxnum},1");
		if($act[0]&&$act[0]['id']){
			$this->delete(" user_id={$uid} AND id<{$act[0]['id']} ");
		}
	}
	
	public function deleteByUser($uid){
		return $this->delete(" user_id={$uid} OR to_user_id={$uid} ");
	}
	
}